package com.pansoft.kline.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.utils.ImageUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ImageSpliceUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.pansoft.kline.adapter.SimpleFragmentPagerAdapter;
import com.pansoft.kline.base.KlineBaseActivity;
import com.pansoft.kline.base.KlineBaseFragment;
import com.pansoft.kline.fragment.DealRealAnalyzeFragment;
import com.pansoft.kline.fragment.DealRealBriefingFragment;
import com.pansoft.kline.fragment.DealRealFundFragment;
import com.pansoft.kline.fragment.KLineChartFragment;
import com.pansoft.kline.fragment.TimeLineChartFragment;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.model.BoursePriceTopBean;
import com.pansoft.kline.model.ConfigCoinBean;
import com.pansoft.kline.model.ConfigMarketBean;
import com.pansoft.kline.model.ConfigSiteBean;
import com.pansoft.kline.model.IndexSelectEvent;
import com.pansoft.kline.model.KIndexSelectEvent;
import com.pansoft.kline.model.SelfSelectRefreshEvent;
import com.pansoft.kline.model.SelfSelectedBean;
import com.pansoft.kline.util.BtcKanNumberFormatUtil;
import com.pansoft.kline.util.KLineUtil;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.kline.widget.ChartIndexPopupWindow;
import com.pansoft.kline.widget.KindexPopupWindow;
import com.pansoft.kline.widget.KlinePopWindowManager;
import com.pansoft.klinelib.chart.KLineView;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.manager.CurrencyAndBourseManager;
import com.pansoft.openplanet.util.TCMathUtil;
import com.qmuiteam.qmui.util.QMUIDrawableHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.ImageUtils;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ThreadManager;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_15_MINUTE;
import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_3_DAY;
import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_DAY;
import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_HOUR;
import static com.pansoft.klinelib.util.KLineConstant.K_LINE_TYPE_MINUTE;
import static com.pansoft.openplanet.constant.MarketConstant.MARKET_DETAIL_TOP_URL;


/**
 * 交易行情
 * 包括K线图等
 *
 * @author will
 */
public class TransactionTrendActivity extends KlineBaseActivity implements View.OnClickListener {

    private TabLayout tabLayout;
    private ConstraintLayout clIndex;
    private TextView tvIndex;
    private ImageView ivIndexTopRight, ivIndexBottomRight,iv_detail;
    private ProgressDialog progressDialog;
    private ConstraintLayout clMainContent, clRootContent;

    private String marketId;

    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;
    /**
     * 隐藏的fragment
     */

    private int hideFragment = 0;
    /**
     * 需要显示的fragment
     */
    private int showFragment = 0;

    private KlineBaseFragment[] mFragments = new KlineBaseFragment[3];
    private ViewPager viewPager;

    /**
     * 加载各指标图表
     **/
    private List<Fragment> fragments = new ArrayList<>();
    private SimpleFragmentPagerAdapter simpleFragmentPagerAdapter;
    private TextView siteTitle;
    private TextView tvPriceUnit;
    TextView tv_real_time_price;
    TextView tv_real_time_change;
    TextView tv_real_time_percent;
    TextView tv_current_turnover;
    TextView tv_deal_high;
    TextView tv_deal_low;
    TextView tv_deal_gross;
    TextView tv_deal_buy;
    TextView tv_deal_sellout;
    TextView tv_deal_rate;
    private ImageView ivRefresh;
    /**
     * 资金
     */

    TextView tv_deal_real_fund;

    View view_deal_real_fund;
    /**
     * 分析
     */

    TextView tv_deal_real_analyze;

    View view_deal_real_analyze;
    /**
     * 简况
     */
    TextView tv_deal_real_briefing;
    View view_deal_real_briefing;

    LinearLayout ll_deal_real_fund;
    LinearLayout ll_deal_real_analyze;
    LinearLayout ll_deal_real_briefing;
    /**
     * 底部切换汇率的ll
     */
    private LinearLayout ll_switch_rote;
    private SmartRefreshLayout smartRefreshLayout;

    //期望的货币单位（默认显示RMB）
    private String wantCurrency = "CNY";
    //上一次请求的顶部数据（用来做比对使用）
    private BoursePriceTopBean.DataBean lastTopDataBean;

    private Timer timer;
    private RefreshTask timerTask;

    /**
     * 底部切换汇率的popWindow
     */
    private PopupWindow bottomPopupWindow;
    int[] location = new int[2];
    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    public static void start(Context context, String marketId) {
        Intent starter = new Intent(context, TransactionTrendActivity.class);
        starter.putExtra("marketId", marketId);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_transaction_trend);
        marketId = getIntent().getStringExtra("marketId");
        wantCurrency = CurrencyAndBourseManager.getCurrencyUnitCode();
        initView(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        startTask();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopTask();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        ((TextView) findViewById(R.id.tv_title)).setText(getResources().getString(R.string.price));
        findViewById(R.id.iv_back).setOnClickListener(this);
        progressDialog = new ProgressDialog(this);
        clMainContent = (ConstraintLayout) findViewById(R.id.cl_main_content);
        clRootContent = (ConstraintLayout) findViewById(R.id.cl_root_view);
        tv_real_time_price = (TextView) findViewById(R.id.tv_real_time_price);
        tv_real_time_change = (TextView) findViewById(R.id.tv_real_time_change);
        tv_real_time_percent = (TextView) findViewById(R.id.tv_real_time_percent);
        tv_current_turnover = (TextView) findViewById(R.id.tv_current_turnover);
        tv_deal_high = (TextView) findViewById(R.id.tv_deal_high);
        tv_deal_low = (TextView) findViewById(R.id.tv_deal_low);
        tv_deal_gross = (TextView) findViewById(R.id.tv_deal_gross);
        tv_deal_buy = (TextView) findViewById(R.id.tv_deal_buy);
        tv_deal_sellout = (TextView) findViewById(R.id.tv_deal_sellout);
        tv_deal_rate = (TextView) findViewById(R.id.tv_deal_rate);
        tv_deal_real_fund = (TextView) findViewById(R.id.tv_deal_real_fund);
        view_deal_real_fund = findViewById(R.id.view_deal_real_fund);
        tv_deal_real_analyze = (TextView) findViewById(R.id.tv_deal_real_analyze);
        view_deal_real_analyze = findViewById(R.id.view_deal_real_analyze);
        tv_deal_real_briefing = (TextView) findViewById(R.id.tv_deal_real_briefing);
        view_deal_real_briefing = findViewById(R.id.view_deal_real_briefing);
        ll_deal_real_fund = (LinearLayout) findViewById(R.id.ll_deal_real_fund);
        ll_deal_real_analyze = (LinearLayout) findViewById(R.id.ll_deal_real_analyze);
        ll_deal_real_briefing = (LinearLayout) findViewById(R.id.ll_deal_real_briefing);
        ll_switch_rote = (LinearLayout) findViewById(R.id.ll_switch_rote);
        siteTitle = (TextView) findViewById(R.id.tv_title_name);
        tvPriceUnit = (TextView) findViewById(R.id.tv_price_unit);
        iv_detail = (ImageView) findViewById(R.id.iv_detail);
        iv_detail.setVisibility(View.VISIBLE);
        ll_deal_real_fund.setOnClickListener(this);
        ll_deal_real_analyze.setOnClickListener(this);
        ll_deal_real_briefing.setOnClickListener(this);
        ll_switch_rote.setOnClickListener(this);
        iv_detail.setOnClickListener(this);
        ivRefresh = (ImageView) findViewById(R.id.iv_refresh);
        ivRefresh.setOnClickListener(this);
        smartRefreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
               //刷新截面数据，除了top的数据
                refreshData();
            }
        });

        tabLayout = (TabLayout) findViewById(R.id.tab);
        viewPager = (ViewPager) findViewById(R.id.view_pager);

        setUpKLineFragmentAdapter();
        viewPager.setAdapter(simpleFragmentPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
        //处理K线指标弹窗
        initKIndexView();
        //处理MA,Boll指标弹窗
        initIndexView();
        //全屏
        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FullScreenChartActivity.launch(TransactionTrendActivity.this, viewPager.getCurrentItem(), marketId);
            }
        });

        selection(ll_deal_real_fund);
        loadFragment();
    }

    private void setUpKLineFragmentAdapter() {
        Fragment[] fragmentArray = {TimeLineChartFragment.newInstance(K_LINE_TYPE_MINUTE, marketId), KLineChartFragment.newInstance(K_LINE_TYPE_15_MINUTE, marketId),
                KLineChartFragment.newInstance(K_LINE_TYPE_HOUR, marketId), KLineChartFragment.newInstance(K_LINE_TYPE_DAY, marketId),
                KLineChartFragment.newInstance(K_LINE_TYPE_3_DAY, marketId)};
        fragments.clear();
        fragments.addAll(Arrays.asList(fragmentArray));
        String[] titleArray = getResources().getStringArray(R.array.array_chart_k_index);
        List<String> titles = Arrays.asList(titleArray);
        //viewPager.setOffscreenPageLimit(fragments.length);
        simpleFragmentPagerAdapter = new SimpleFragmentPagerAdapter(getSupportFragmentManager(), fragments, titles);
    }

    /**
     * 刷新 包括三个菜单以及K线
     */
    private void refreshData() {
        if (mFragments!=null){
            for (int i = 0; i < mFragments.length; i++) {
                KlineBaseFragment fragment = mFragments[i];
                fragment.requestData();
            }
        }

        //刷新K线图
        refreshKChart();

        smartRefreshLayout.finishRefresh(2000);
    }

    private void refreshKChart() {
        if (viewPager.getCurrentItem() == 0) {
            ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem())).reloadData();
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem() + 1)).reloadData("");
        } else if (viewPager.getCurrentItem() == 1){
            ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem() - 1)).reloadData();
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).reloadData("");
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem() + 1)).reloadData("");
        } else if (viewPager.getCurrentItem() == fragments.size() - 1) {
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem() - 1)).reloadData("");
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).reloadData("");
        } else {
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem() - 1)).reloadData("");
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).reloadData("");
            ((KLineChartFragment) fragments.get(viewPager.getCurrentItem() + 1)).reloadData("");
        }
    }


    private void initKIndexView() {
        final View tabItemView = LayoutInflater.from(this).inflate(R.layout.chart_layout_tab_item, null, false);
        tabLayout.getTabAt(4).setCustomView(tabItemView);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 4) {
                    KindexPopupWindow.setKIndexTabSelected(TransactionTrendActivity.this, tabLayout);
                } else {
                    KindexPopupWindow.setKIndexTabUnSelected(TransactionTrendActivity.this, tabLayout);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                if (tab.getPosition() == 4) {
                    KindexPopupWindow.setKIndexTabShowPop(TransactionTrendActivity.this, tabLayout);
                    new KindexPopupWindow(TransactionTrendActivity.this,
                            TransactionTrendActivity.this.getWindow().getDecorView(), tabLayout, ((TextView) tab.getCustomView().findViewById(R.id.tv_K_index)).getText().toString());
                }
            }
        });
    }

    private void initIndexView() {
        clIndex = (ConstraintLayout) findViewById(R.id.cl_index);
        tvIndex = (TextView) findViewById(R.id.tv_index);
        ivIndexTopRight = (ImageView) findViewById(R.id.iv_full_right_top_triangle);
        ivIndexBottomRight = (ImageView) findViewById(R.id.iv_full_right_bottom_triangle);

        clIndex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivIndexTopRight.setVisibility(View.VISIBLE);
                ivIndexBottomRight.setVisibility(View.INVISIBLE);
                new ChartIndexPopupWindow(TransactionTrendActivity.this,
                        TransactionTrendActivity.this.getWindow().getDecorView(), clIndex);
            }
        });
    }

    /**
     * 1分K，日K等指标选择
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSolveKIndexSelectedEvent(KIndexSelectEvent event) {
        KindexPopupWindow.setTabIndexText(TransactionTrendActivity.this, tabLayout, event.getIndexName());
        ((KLineChartFragment) fragments.get(4)).reloadData(event.getIndex());
    }

    /**
     * MA， KDJ等指标选择, 更改当前界面视图
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onIndexSelectedEvent(IndexSelectEvent event) {
        switch (event.getIndex()) {
            case "MA":
                KLineView.CHART_MAIN_INDEX = "MA";
                if (viewPager.getCurrentItem() == 0) {
                    ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem())).showMa();
                } else {
                    ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).showMa();
                }
                break;
            case "BOLL":
                KLineView.CHART_MAIN_INDEX = "BOLL";
                if (viewPager.getCurrentItem() == 0) {
                    ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem())).showBoll();
                } else {
                    ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).showBoll();
                }
                break;
            case "MACD":
                KLineView.CHART_SUB_INDEX = "MACD";
                if (viewPager.getCurrentItem() == 0) {
                    ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem())).showMacd();
                } else {
                    ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).showMacd();
                }
                break;
            case "KDJ":
                KLineView.CHART_SUB_INDEX = "KDJ";
                if (viewPager.getCurrentItem() == 0) {
                    ((TimeLineChartFragment) fragments.get(viewPager.getCurrentItem())).showKdj();
                } else {
                    ((KLineChartFragment) fragments.get(viewPager.getCurrentItem())).showKdj();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.ll_deal_real_fund) {
            //资金
            selection(ll_deal_real_fund);
            showFragment = FIRST;
            showHideFragment(mFragments[showFragment], mFragments[hideFragment]);
            hideFragment = FIRST;

        } else if (i == R.id.ll_deal_real_analyze) {
            //分析
            selection(ll_deal_real_analyze);
            showFragment = SECOND;
            showHideFragment(mFragments[showFragment], mFragments[hideFragment]);
            hideFragment = SECOND;

        } else if (i == R.id.ll_deal_real_briefing) {
            //简况
            selection(ll_deal_real_briefing);
            showFragment = THIRD;
            showHideFragment(mFragments[showFragment], mFragments[hideFragment]);
            hideFragment = THIRD;

        } else if (i == R.id.iv_back) {
            //返回
            finish();
        }else if(i == R.id.ll_switch_rote){
            //底部切换汇率的点击事件
            initBottomPopWindow();

        }else if(i == R.id.iv_detail){
            //右上角的按钮的点击事件
            KlinePopWindowManager.showOptionalAndSharePop(this, iv_detail, marketId,
                    new KlinePopWindowManager.OnMenuSelectedListener() {
                @Override
                public void onShare() {
                    shareKLinePic();
                }

                @Override
                public void onAddSelect() {
                    SelfSelectedBean selfSelectedBean = new SelfSelectedBean();
                    selfSelectedBean.setMarketId(marketId);
                    selfSelectedBean.setUserName(EnvironmentVariable.getUserName());
                    DaoSessionUtil.getInstance().getSelfSelectedBeanDao()
                            .insert(selfSelectedBean);
                    ToastUtils.showShort(R.string.chart_already_added);
                    EventBus.getDefault().postSticky(new SelfSelectRefreshEvent());
                }

                @Override
                public void onDeleteSelect(long id) {
                    SelfSelectedBean selfSelectedBean = new SelfSelectedBean(id, marketId,
                            EnvironmentVariable.getUserName());
                    DaoSessionUtil.getInstance().getSelfSelectedBeanDao()
                            .delete(selfSelectedBean);
                    ToastUtils.showShort(R.string.chart_already_deleted);
                    EventBus.getDefault().postSticky(new SelfSelectRefreshEvent());
                }

            });
        } else if (i == R.id.iv_refresh) {
            refreshKChart();
        }
    }

    /**
     * 设置tab按钮变化
     *
     * @param linearLayout
     */
    private void selection(LinearLayout linearLayout) {
        ll_deal_real_fund.setSelected(false);
        ll_deal_real_analyze.setSelected(false);
        ll_deal_real_briefing.setSelected(false);
        linearLayout.setSelected(true);

    }

    /**
     * 加载资金 分析 简况的fragment
     */
    private void loadFragment() {
        KlineBaseFragment firstFragment = findFragment(DealRealFundFragment.class);
        if (firstFragment == null) {
            mFragments[FIRST] = DealRealFundFragment.newInstance(marketId);
            mFragments[SECOND] = DealRealAnalyzeFragment.newInstance(marketId);
            mFragments[THIRD] = DealRealBriefingFragment.newInstance(marketId);
            loadMultipleRootFragment(R.id.fl_bottom_content, FIRST, mFragments);
        } else {
            // 这里库已经做了Fragment恢复,所有不需要额外的处理了, 不会出现重叠问题

            // 这里我们需要拿到mFragments的引用,也可以通过getChildFragmentManager.findFragmentByTag自行进行判断查找(效率更高些),用下面的方法查找更方便些
            mFragments[FIRST] = firstFragment;
            mFragments[SECOND] = (KlineBaseFragment) findFragment(DealRealAnalyzeFragment.class);
            mFragments[THIRD] = (KlineBaseFragment) findFragment(DealRealBriefingFragment.class);

        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        KLineView.CHART_MAIN_INDEX = "MA";
        KLineView.CHART_SUB_INDEX = "MACD";
    }

    /**
     * 顶部的数据
     */
    private void loadTopData() {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("marketID", marketId);
        JFCommonRequestManager.getInstance(this).requestGetByAsyn(TAG, MARKET_DETAIL_TOP_URL, hashMap,
                new JFCommonRequestManager.ReqCallBack<String>() {
                    @Override
                    public void onReqSuccess(String result) {
                        smartRefreshLayout.finishRefresh(100);

                        try {
                            BoursePriceTopBean topBean = new Gson().fromJson(result, BoursePriceTopBean.class);
                            if (topBean.getCode() != 0) {
                                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                                return;
                            }
                            refreshTopData(topBean);
                        } catch (Exception e) {
                            e.printStackTrace();
                            ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                        }
                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                        //fixme 返回时经常触发，在上一界面toast
//                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
                        smartRefreshLayout.finishRefresh(100);
                    }
                });

    }

    /**
     * 刷新顶部数据
     *
     * @param topBean
     */
    private void refreshTopData(BoursePriceTopBean topBean) {
        BoursePriceTopBean.DataBean itemBean = topBean.getData();
        if (lastTopDataBean == null) {
            lastTopDataBean = itemBean;
        }
        ConfigMarketBean marketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(marketId);
        ConfigCoinBean coinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(marketBean.getCoin());
        ConfigSiteBean siteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(marketBean.getSite());

        String currency = marketBean.getCurrency();
        siteTitle.setText(coinBean.getCoinKey() + "/" + currency + "," + siteBean.getTitle());

        double high = itemBean.getHigh();
        double low = itemBean.getLow();
        double last = itemBean.getLast();
        double open = itemBean.getOpen();
        double buy = itemBean.getBuy();
        double sell = itemBean.getSell();

        high = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, high);
        low = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, low);
        buy = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, buy);
        sell = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, sell);
        last = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, last);
        tvPriceUnit.setText(KLineUtil.getCurrencySymbol(wantCurrency));
        //最高
        tv_deal_high.setText(BtcKanNumberFormatUtil.assignNumberFormat(high, 7, 6) + "");
        //最低
        tv_deal_low.setText(BtcKanNumberFormatUtil.assignNumberFormat(low, 7, 6) + "");
        //买1
        tv_deal_buy.setText(BtcKanNumberFormatUtil.assignNumberFormat(buy, 7, 6) + "");
        //卖1
        tv_deal_sellout.setText(BtcKanNumberFormatUtil.assignNumberFormat(sell, 7, 6) + "");
        //成交量
        tv_current_turnover.setText(MarketNumberUtils.amountConversion(itemBean.getVol()));
        //成交额
        double gross = TCMathUtil.mul(itemBean.getVol(), last);
        tv_deal_gross.setText(MarketNumberUtils.amountConversion(gross));
        //last价格
        tv_real_time_price.setText(BtcKanNumberFormatUtil.assignNumberFormat(last, 7, 6) + "");
        //费率
        String rate = siteBean.getFee();
        if (rate == null || "".equals(rate)) {
            rate = "0.2%";
        } else {
            rate = rate + "%";
        }
        tv_deal_rate.setText(rate);
        //百分比使用 last open 计算
        double balance = TCMathUtil.sub(itemBean.getLast(), itemBean.getOpen());
        //banlance 转换成人民币
        double wantBalance = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), wantCurrency, balance);
        //计算百分比
        String percent = BtcKanNumberFormatUtil.getPercent(TCMathUtil.div(balance, open, 4));
        String change = BtcKanNumberFormatUtil.assignNumberFormat(wantBalance, 7, 6);
        tv_real_time_percent.setText(BtcKanNumberFormatUtil.addNumberSign(percent));
        tv_real_time_change.setText(BtcKanNumberFormatUtil.addNumberSign(change));
        if (percent.contains("-")) {
            tv_real_time_percent.setTextColor(getResources().getColor(R.color.decreasing_color));
            tv_real_time_change.setTextColor(getResources().getColor(R.color.decreasing_color));
        } else {
            tv_real_time_percent.setTextColor(getResources().getColor(R.color.increasing_color));
            tv_real_time_change.setTextColor(getResources().getColor(R.color.increasing_color));
        }

        //设置涨跌
        if (lastTopDataBean.getLast() < itemBean.getLast()) {
            //上涨
            itemBean.setLastTrendType(1);
            tv_real_time_price.setTextColor(getResources().getColor(R.color.increasing_color));
            tvPriceUnit.setTextColor(getResources().getColor(R.color.increasing_color));

        } else if (lastTopDataBean.getLast() > itemBean.getLast()) {
            itemBean.setLastTrendType(-1);
            //下跌
            tv_real_time_price.setTextColor(getResources().getColor(R.color.decreasing_color));
            tvPriceUnit.setTextColor(getResources().getColor(R.color.decreasing_color));
        } else {
            itemBean.setLastTrendType(lastTopDataBean.getLastTrendType());
        }
        //设置涨跌箭头
        if (itemBean.getLastTrendType() == 1) {
            tv_real_time_price.setText(tv_real_time_price.getText() + "↑");

        } else if (itemBean.getLastTrendType() == -1) {
            tv_real_time_price.setText(tv_real_time_price.getText() + "↓");

        }
        // 设置上一次数据
        lastTopDataBean = itemBean;
    }

    /**
     * 开始定时刷新任务
     */
    private void startTask() {

        stopTask();
        timer = new Timer();
        timerTask = new RefreshTask();
        timer.schedule(timerTask, 0, 3000);
    }

    /**
     * 结束定时刷新任务
     */
    private void stopTask() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
            timerTask = null;
        }
    }

    public class RefreshTask extends TimerTask {

        @Override
        public void run() {
//            LogUtils.i("执行刷新");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    loadTopData();
                }
            });
        }
    }

    /**
     * 初始化popwindow
     */
    private void initBottomPopWindow(){
        if(bottomPopupWindow!=null){
            if(bottomPopupWindow.isShowing()){
//                bottomPopupWindow.dismiss();
                LogUtils.e("showwww----22222222");
            }else {
                LogUtils.e("showwww----1111");
                bottomPopupWindow.showAtLocation(ll_switch_rote,Gravity.NO_GRAVITY, location[0], location[1] - bottomPopupWindow.getContentView().getMeasuredHeight());
            }

        }else {
            View contentView = LayoutInflater.from(this).inflate(R.layout.popwindow_chart_detail_bottom_rote,null);
            contentView.findViewById(R.id.ll_detail_bottom_original).setOnClickListener(this);
            contentView.findViewById(R.id.ll_detail_bottom_cny).setOnClickListener(this);
            contentView.findViewById(R.id.ll_detail_bottom_usd).setOnClickListener(this);
            bottomPopupWindow = new PopupWindow(contentView,LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            // 设置PopupWindow是否能响应外部点击事件
            bottomPopupWindow.setOutsideTouchable(true);
            bottomPopupWindow.setTouchable(false);
            bottomPopupWindow.setFocusable(true);
            // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
            bottomPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            ll_switch_rote.getLocationOnScreen(location);
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            contentView.measure(w,h);
            bottomPopupWindow.showAtLocation(ll_switch_rote,Gravity.NO_GRAVITY, location[0], location[1] - bottomPopupWindow.getContentView().getMeasuredHeight());
        }
    }

    /**
     * 分享行情图片
     */
    public void shareKLinePic() {
        progressDialog.setMessage(ResStringUtil.getString(R.string.common_text_loading));
        progressDialog.show();
        ThreadManager.getThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                //拼接图片
                Bitmap rawbitmap = QMUIDrawableHelper.createBitmapFromView(clMainContent);
                Bitmap bitmap = ImageSpliceUtil.mergeBitmap_TB(rawbitmap,
                        BitmapFactory.decodeResource(getResources(), R.drawable.share_botton_join), true);
                //文件保存路径
                final String fielPath = ImageUtil.chatpath
                        + System.currentTimeMillis() + ".png";
                //原图片路径
                final String fileNoBarcodePath = ImageUtil.chatpath + System.currentTimeMillis() + "raw.png";
                //保存拼接图片
                ImageUtils.save(bitmap, fielPath, Bitmap.CompressFormat.PNG, true);
                //保存原图片
                ImageUtils.save(rawbitmap, fileNoBarcodePath, Bitmap.CompressFormat.PNG, true);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!isDestroyed()) {
                            progressDialog.dismiss();
                            //调用友盟分享
                            try {
                                ShareKLineActivity.start(TransactionTrendActivity.this, fielPath, fileNoBarcodePath);
                            } catch (Exception e) {
                                LogUtils.d("没有找到分享的类");
                            }
                        }
                    }
                });
            }
        });
    }
}
